package com.itxiuyixiu.homework.security.service;

import com.itxiuyixiu.homework.entity.dao.AdminDao;
import com.itxiuyixiu.homework.entity.model.Admin;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author 黄磊
 * @date 2020/3/6
 */
@Component
public class AdminDetailsServiceImpl implements UserDetailsService {
    private final AdminDao adminDao;

    public AdminDetailsServiceImpl(AdminDao adminDao) {
        this.adminDao = adminDao;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Optional<Admin> adminOptional = adminDao.findById(s);
        if (adminOptional.isPresent()) {
            Admin admin = adminOptional.get();
            return new User(admin.getUsername(), admin.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(admin.getAuthorities()));
        } else {
            throw new UsernameNotFoundException("管理员：" + s + "没有被找到");
        }
    }
}
